//
//  OAuthViewController.swift
//  WeiBo
//
//  Created by 江潘 on 15/6/26.
//  Copyright © 2015年 江潘. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    // 设置接口需要参数
    private let App_Key = "354820744"
    private let App_Secret = "7f46165266da9f6c7758e4d08fd3409d"
    private let redirect_uri = "http://www.baidu.com"
    private let redirect_uris = "https://www.baidu.com"
    
    // 懒加载webview
    lazy var webV:UIWebView = {
    
        let webV = UIWebView()
        
        return webV
        
    }()
    // loadView中将控制器的根view换成webview
    override func loadView() {
        
        view = webV
        
        webV.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "clickClose")
        navigationItem.title = "新浪微博"
        
        // 调用加载微博授权页
        loadOAuthPage()
    }
    
    func loadOAuthPage(){
        
        let URLString = "https://api.weibo.com/oauth2/authorize?client_id=\(App_Key)&redirect_uri=\(redirect_uri)"
        
        let URL = NSURL(string: URLString)
        
        let request = NSURLRequest(URL: URL!)
        
        webV.loadRequest(request)
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request)
        
        let url = String(request.URL!)
        
        if url.hasPrefix("https://api.weibo.com"){
        
           return true
            
        } else if url.hasPrefix(redirect_uri) {
            
            let subStr = request.URL!.query!
            
             print(subStr)
            
            if subStr.hasPrefix("code="){
                
                let code = subStr.substringFromIndex(advance((subStr.startIndex), 5))
                
                ///  用授权码获换取访问令牌
                loadAccessToken(code)
                
                print(code)
                
                return false
                
            } else {
            
                clickClose()
            }
      }
        
    return false
 }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func clickClose(){
        
        SVProgressHUD.dismiss()
    
        dismissViewControllerAnimated(true , completion: nil)
    }
    
    /// 用授权码获换取访问令牌方法
    private func loadAccessToken(code:String){
        
        let urlStr = "oauth2/access_token"
        let params = ["client_id":App_Key,
            "client_secret":App_Secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri]
        
        
        NetworkTools.sharedNewworkTools().POST(urlStr, parameters: params, success: { (_ , JSON) -> Void in
            
            let account = UserAccount(InfoDict: JSON as![String:AnyObject])
            
            // 闭包中调用其他类的方法没有提示
            account.loadUserInfo({ (account, error) -> () in
                
                if account != nil{
                    
                    sharedAccount = account
                    
                   NSNotificationCenter.defaultCenter().postNotificationName(noticeName, object: false)
                    
                    print(account)
                    
                    return
                }
                
                print(error)
                
                SVProgressHUD.showErrorWithStatus("您的网络不给力...")
            })
            
            }, failure: { (_ , error) -> Void in
                
              print(error)
                
              SVProgressHUD.showErrorWithStatus("您的网速不给力")
        })
    }
}
